package com.gipson.amc.controller;

import com.dsbj.common.msg.ResponseMessage;
import com.gipson.amc.entity.Role;
import com.gipson.amc.entity.User;
import com.gipson.amc.model.Menu;
import com.gipson.amc.model.request.LoginRequest;
import com.gipson.amc.service.basicdata.AuthorityService;
import com.gipson.amc.service.basicdata.RoleService;
import com.gipson.amc.service.basicdata.UserService;
import com.gipson.amc.utils.Constants;
import com.gipson.amc.utils.PasswordHelper;
import com.gipson.amc.utils.security.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/sys")
public class SysController extends BaseController{

    private Logger logger = LoggerFactory.getLogger(SysController.class);


    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthorityService authorityService;

    @Autowired
    private PasswordHelper passwordHelper;


    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @GetMapping("/notPermit")
    public String notPermit(){
        return Constants.NO_PERMISSION_PAGE;
    }

    @RequestMapping("/index")
    public String index(HttpServletRequest request, ModelMap modelMap){

        logger.debug("进入了首页...");

        User user = ShiroUtils.getCurrentUser();
        List<Menu> menuList = user.getMenus();
        List<Menu> sortedMenuList = new ArrayList<>();

        /*
        * 构建菜单上下级
        * */

        sortedMenuList = menuList.stream().filter(x->x.getParentId().equalsIgnoreCase("")).map(x->{
            x.setSubMenus(menuList.stream().filter(y->y.getParentId().equalsIgnoreCase(x.getId())).sorted(Comparator.comparing(Menu::getSortNo)).collect(Collectors.toList()));
            return x;
        }).sorted(Comparator.comparing(Menu::getSortNo)).collect(Collectors.toList());

        request.setAttribute("menuList",sortedMenuList);

        request.getSession().setAttribute("CURRENT_USER",user);
        return "index";
    }

    @RequestMapping("welcome")
    public String welcome(){
        return "welcome";
    }

    @PostMapping("/doLogin")
    @ResponseBody
    public ResponseMessage doLogin(LoginRequest loginRequest) {
        UsernamePasswordToken token = new UsernamePasswordToken(loginRequest.getUsername(), loginRequest.getPassword(),loginRequest.getRememberMe().equals("1")?true:false);
        Subject subject = SecurityUtils.getSubject();
       try {
            subject.login(token);
        } catch (IncorrectCredentialsException ice) {
            return ResponseMessage.error("密码不对!");
        } catch (UnknownAccountException uae) {
            return ResponseMessage.error("用户名不对!");
        }

        User user = userService.findUserByName(loginRequest.getUsername());
        user.setPasswordShown(loginRequest.getPassword());
        subject.getSession().setAttribute("currentUser", user);
        return ResponseMessage.okWithMsg("登录成功!");
    }

   /* @RequestMapping("/addUser")
    @ResponseBody
    public ResponseMessage addUser(){

        *//*User user = new User();
        user.setUsername("admin");
        user.setPassword("123456");
        user.setName("张键");
        user.setUserCode("D501925519");
        passwordHelper.encryptPassword(user);
        userService.addUser(user);

        Role role = new Role();

        role.setRoleCode("admin");
        role.setRoleName("系统管理员");
        roleService.addRole(role);*//*
        String newPassword = new SimpleHash("md5", "123456",ByteSource.Util.bytes("aad70c9fa05898047b21816effe3eb33"), 1024).toHex();

        return ResponseMessage.ok(newPassword);
    }*/

    @RequestMapping("/ssoLogin")
    public String ossLogin(HttpServletRequest request,String appId){

        User user = ShiroUtils.getCurrentUser();
        String ssoUrl = String.format("redirect:http://10.10.70.37:8910/sys/ssoLogin?username=%s&password=%s",user.getUsername(),user.getPasswordShown());
        return ssoUrl;
    }


}
